/* transform.interceptor.ts */

import {
  Injectable,
  NestInterceptor,
  CallHandler,
  ExecutionContext,
  ForbiddenException,
} from '@nestjs/common';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((data) => {
        let message: string = '请求成功';
        let success: boolean = true;
        if (data.status && data.status.toString().startsWith('4')) {
          message = data.message;
          success = false;
        }
        return {
          data,
          code: 200,
          message,
          success,
        };
      }),
    );
  }
}

@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      catchError((err: any): any => {
        console.log(err);
        if (err?.errno === 1062) {
          throw new ForbiddenException(err.message);
        } else if (err.status == 401) {
          throw new ForbiddenException(err.message);
        } else {
          return next.handle();
        }
      }),
    );
  }
}
